package com.mdd.maduoduo.view.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class BaseWebView extends WebView {

    private WebViewListener mWebViewListener;

    public BaseWebView(Context context) {
        this(context, null);
    }

    public BaseWebView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BaseWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initWebView();
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        // 基本设置
        WebSettings settings = getSettings();
        settings.setJavaScriptEnabled(true); // 启用JS
        settings.setDomStorageEnabled(true); // 启用DOM存储
        settings.setDatabaseEnabled(true); // 启用数据库
        settings.setCacheMode(WebSettings.LOAD_DEFAULT); // 缓存模式

        // 自适应屏幕
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setSupportZoom(true); // 支持缩放
        settings.setBuiltInZoomControls(true); // 显示缩放控件
        settings.setDisplayZoomControls(false); // 隐藏原生缩放控件

        // 其他设置
        settings.setAllowFileAccess(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setLoadsImagesAutomatically(true);
        settings.setDefaultTextEncodingName("utf-8");

        // 5.0以上开启混合模式加载
        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        // 设置WebViewClient
        setWebViewClient(new InnerWebViewClient());

        // 设置WebChromeClient
        setWebChromeClient(new InnerWebChromeClient());

        // 防止内存泄漏
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            setWebContentsDebuggingEnabled(true);
        }
    }

    /**
     * 设置WebView监听器
     */
    public void setWebViewListener(WebViewListener listener) {
        this.mWebViewListener = listener;
    }

    /**
     * 内部WebViewClient，处理各种回调
     */
    private class InnerWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (mWebViewListener != null && mWebViewListener.shouldOverrideUrlLoading(view, url)) {
                return true;
            }
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (mWebViewListener != null) {
                mWebViewListener.onPageFinished(view, url);
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            if (mWebViewListener != null) {
                mWebViewListener.onReceivedError(view, errorCode, description, failingUrl);
            }
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            if (mWebViewListener != null) {
                return mWebViewListener.shouldInterceptRequest(view, request);
            }
            return super.shouldInterceptRequest(view, request);
        }
    }

    /**
     * 内部WebChromeClient，处理进度、标题等
     */
    private class InnerWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (mWebViewListener != null) {
                mWebViewListener.onProgressChanged(view, newProgress);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (mWebViewListener != null) {
                mWebViewListener.onReceivedTitle(view, title);
            }
        }
    }

    /**
     * WebView监听接口
     */
    public interface WebViewListener {
        boolean shouldOverrideUrlLoading(WebView view, String url);

        void onPageFinished(WebView view, String url);

        void onReceivedError(WebView view, int errorCode, String description, String failingUrl);

        void onProgressChanged(WebView view, int newProgress);

        void onReceivedTitle(WebView view, String title);

        WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request);
    }

    /**
     * 销毁WebView，防止内存泄漏
     */
    public void destroyWebView() {
        loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
        clearHistory();
        ((android.view.ViewGroup) getParent()).removeView(this);
        destroy();
    }
}
